#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<wchar.h>
#include<locale.h>
char *root;
void printUsage(char *cmd){
	printf("program can make format for c source\n");
	printf("parameter of source file must use relative path\n");
	printf("Usage:\n");
	printf("%s <file>\n",cmd);
}
void formatCode(char *source){
	setLocale(LC_ALL,"zh_CN.UTF-8");
	struct stat attr;
	FILE* f=fopen(source,"r");
	if(f==NULL){
		printf("can not open file:%s",source);
		return;
	}
	fstat(f,&attr);
	int count=0;
	wchar_t *buf=malloc((attr.off_t+1)/2);
	int indent=0;
	for(int ch=fgetc(f);ch>=0;ch=fgetc(f)){
		if(ch==' '||ch=='\t'||ch=='\n'){
		}else{
			for(int index=0;index<indent;index++){
				fputc('\t',stdout);
			}
			fputc(ch,stdout);
			int enumRange=0;
			int enumTrans=0;
			int cutSpace=0;
			for(int ch=fgetc(f);ch>=0;ch=fgetc(f)){
				if(ch=='\n'){
					fputc(ch,stdout);
					break;
				}else if(ch=='\''){
					cutSpace=0;
					fputc(ch,stdout);
					if(enumTrans==1)continue;
					if(enumRange==0){enumRange=1;}
					else if(enumRange==1)enumRange=0;
				}else if(ch=='"'){
					cutSpace=0;
					fputc(ch,stdout);
					if(enumRange==0)enumRange=2;
					else if(enumRange==2)enumRange=0;
				}else if(ch=='\\'){
					cutSpace=0;
					fputc(ch,stdout);
					if(enumTrans==0)enumTrans=1;
					if(enumTrans==1)enumTrans=0;
				}else if(ch=='{'){
					cutSpace=0;
					fputc(ch,stdout);
					if(enumRange==0)indent++;
				}else if(ch=='}'){
					cutSpace=0;
					fputc(ch,stdout);
					if(enumRange==0)indent--;
				}else if(ch==' '){
					if(enumRange==0){
						if(cutSpace==0){cutSpace=1;fputc(' ',stdout);}
					}
				}else if(ch=='\t'){
					if(enumRange==0){
						if(cutSpace==0){cutSpace=1;fputc(' ',stdout);}
					}
				}else{
					cutSpace=0;
					fputc(ch,stdout);
				}
			}
		}
	}
	fclose(f);
}
int main(int argc,char *argv[]){
	if(argc<2){
		char *program=argv[0];
		printUsage(program);
	}else{
		char* i=strrchr(argv[0],'\\');
		char* path;
		if(i){
			*(i+1)='\0';
			path=malloc(strlen(argv[0])+strlen(argv[1]));
			strcpy(path,argv[0]);
			strcat(path,argv[1]);
		}else{
			path=malloc(strlen(argv[1]));
			strcpy(path,argv[1]);
		}
		formatCode(path);
		free(path);
	}
}